package kyssion.leetcode.num51_100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class code90_子集2 {
    public static void main(String[] args) {
        new code90_子集2().subsetsWithDup(
                new int[]{1, 4, 4, 4, 4}
        );
    }

    /**
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> listList = new ArrayList<>();
        if (nums.length <= 0) {
            return listList;
        }
        Arrays.sort(nums);
        listList.add(new ArrayList<>());
        int before = 0;
        for (int a = 0; a < nums.length; a++) {
            if (a == 0 || nums[a] == nums[a - 1]) {
                int old = listList.size();
                addAll(listList, before, nums[a]);
                before = old;
            } else {
                before = listList.size();
                addAll(listList, 0, nums[a]);
            }
        }
        return listList;
    }

    private void addAll(List<List<Integer>> lists, int start, int num) {
        int length = lists.size();
        for (int a = start; a < length; a++) {
            List<Integer> item = new ArrayList<>(lists.get(a));
            item.add(num);
            lists.add(item);
        }
    }


    /**
     * 这种写法的思路就是将特殊的重复项单独的抽离出来,然后最后进行处理的方法
     */
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> subsetsWithDup2(int[] nums) {
        Arrays.sort(nums);
        dfs(nums, 0);
        return res;
    }

    private void dfs(int[] nums, int u){
        if (u == nums.length){
            res.add(new ArrayList(path));
            return ;
        }

        int k = u;
        while (k < nums.length && nums[k] == nums[u])
            k++;
        dfs(nums, k);
        for (int i = u; i < k; i ++){
            path.add(nums[i]);
            dfs(nums, k);
        }
        while(k-- > u)
            path.removeLast();
    }
}
